package com.example.roomtest

import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.preference.*

class SettingsActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.settings_activity)
        supportFragmentManager
            .beginTransaction()
            .replace(R.id.settings, SettingsFragment())
            .commit()
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
    }

    class SettingsFragment : PreferenceFragmentCompat(), Preference.OnPreferenceChangeListener {
        val pm by lazy { preferenceManager }
        val sp by lazy { PreferenceManager.getDefaultSharedPreferences(activity) }
        override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
            //设置页面的布局文件
            setPreferencesFromResource(R.xml.root_preferences, rootKey)
        }

        override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
            super.onViewCreated(view, savedInstanceState)
            //为EditTextPreference设置数据改变的监听(数据没有改变也会触发该事件,只要点了OK键就会触发)
            val signateditTextPreferencere = pm.findPreference<EditTextPreference>("signature")
            signateditTextPreferencere?.onPreferenceChangeListener = this
            //为ListPreference设置数据改变的监听
            val listPreference = pm.findPreference<ListPreference>("reply")
            listPreference?.onPreferenceChangeListener = this
        }


        //点击的触发事件
        override fun onPreferenceTreeClick(preference: Preference?): Boolean {
            val sp = PreferenceManager.getDefaultSharedPreferences(activity)

            Log.i("TAG", "${preference?.key} ");
            when (preference?.key) {
                "reply" -> {
                    val string = sp.getString("reply", "haha")
                    Log.i("TAG", "$string ");
                }
            }
            return super.onPreferenceTreeClick(preference)
        }

        //数据改变会触发的事件,
        override fun onPreferenceChange(preference: Preference?, newValue: Any?): Boolean {

            when (preference?.key) {
                "reply" -> {
                    //在这里得到的是上一次的结果
                    val string = sp.getString("reply", "haha")
                    Log.i("TAG", "$string ");
                    //在这里得到的是最新改变的结果
                    Log.i("TAG", "数据改变了 ${newValue.toString()} ");
                }
                "signature" -> {
                    //在这里得到的是上一次的结果
                    val string = sp.getString("reply", "hehe")
                    Log.i("TAG", "$string ");
                    //在这里得到的是最新改变的结果
                    Log.i("TAG", "数据改变了 ${newValue.toString()} ");
                }
            }

            return true
        }


    }
}